package com.caht.controller.user;

import com.caht.entity.Topic;
import com.caht.result.Result;
import org.apache.tomcat.jni.Multicast;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件上传接口
 */
@RestController
@RequestMapping("/user/upload")
public class uploadFileComtroller {
    String path = "D:\\HTML_JS\\项目\\博客网\\caht\\caht_servier\\src\\main\\resources\\img";
    @PostMapping("/file")
    public Result<String> MultipartFile(MultipartFile file){
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        //设置文件名防止文件名重复
        String filename = System.currentTimeMillis() +  file.getOriginalFilename();
        //设置文件存放路径
        String filepath = path;
        File dest = new File(filepath + filename);
        File parentFile = dest.getParentFile();
        if (!parentFile.exists()){
            parentFile.mkdirs();
        }
        //        存储到数据库的相对文件地址
        String addmysql="/img/"+filename;
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success(addmysql);
    }

    @PostMapping("/files")
    public Result<List<String>> MultipartFile(@RequestParam("image") MultipartFile[] file){
        String filename = "";
        List<String> addmysql =new ArrayList<>();
        for (int i = 0; i < file.length; i++) {
            System.out.println(file[i].getName());
            System.out.println(file[i].getOriginalFilename());
            //设置文件名防止文件名重复
            filename = System.currentTimeMillis() +  file[i].getOriginalFilename();
            //设置文件存放路径
            String filepath = "D:\\HTML_JS\\项目\\博客网\\caht\\caht_servier\\src\\main\\resources\\img\\";
            File dest = new File(filepath + filename);
            File parentFile = dest.getParentFile();
            if (!parentFile.exists()){
                parentFile.mkdirs();
            }
            //存储到数据库的相对文件地址
            addmysql.add("/img/"+filename);
            try {
                file[i].transferTo(dest);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return Result.success(addmysql);
    }


}
